<?php

namespace humhub\modules\api\controllers;

use Yii;
use yii\web\UnauthorizedHttpException;
use humhub\modules\space\models\Space;
use humhub\modules\user\models\User;
use humhub\modules\user\widgets\UserListBox;
use humhub\modules\space\models\Setting;
use \humhub\modules\post\models\Post;

use yii\filters\auth\CompositeAuth;
use yii\filters\auth\HttpBearerAuth;
#use yii\filters\auth\HttpBasicAuth;
#use yii\filters\auth\QueryParamAuth;

/**
 * 发布、编辑dashboard和space内容
 */
class PostccController extends Base2Controller
{

    /**
     * @inheritdoc
     */
    public function init(){
        $cClass = \Yii::$app->request->post('containerClass');
        if( $cClass == 'user' ){
            $_GET['uguid'] = \Yii::$app->request->post('containerGuid');
            $_POST['containerClass'] = 'humhub\modules\user\models\User';
        }
        if( $cClass == 'space' ){
            $_GET['sguid'] = \Yii::$app->request->post('containerGuid');
            $_POST['containerClass'] = 'humhub\modules\space\models\Space';
        }

        parent::init();
    }

    /**
     * @inheritdoc
     */
    public function behaviors(){
        $behaviors = parent::behaviors();
        $behaviors['authenticator'] = [
            'class' => CompositeAuth::className(),
            'authMethods' => [
                //QueryParamAuth::className(),
                HttpBearerAuth::className(),
            ],
        ];
        return $behaviors;
    }

    /**
     * 发布dashboard和space内容
     *
     * POST /api/postcc
     *
     * post.containerClass 发布类型，[=user]发布到dashboard，[=space]发布到space
     *
     * post.containerGuid  类型GUID，其值为别为space或user的guid
     *
     * post.message        发布的内容
     *
     * post.visibility     [=1]公共, [=0]默认私有
     *
     * post.fileList       上传文件，值为文件的guid，每个guid需以逗号[,]开头
     *
     * post.notifyUserInput 通知(Notify)用户，值为用户的guid，每个guid需以逗号[,]结尾
     *
     * post.p_type 发布的post类型：=0图文、=3视频、 =4八卦
     *
     * p_secs  视频时间:秒
     *
     * post.p_title 发布的八卦话题
     *
     * @return array 新post的id信息等
     */
    public function actionCreate(){
        //$a = array(); $a[] = Yii::$app->user->isGuest; $a[] = Yii::$app->user->id; $a[] = Yii::$app->user->identity; return $a;
        /**
         * user  用户表 id = user_id, :guid, wall_id=wall.id
         * space 空间表 id = spaceId, :guid, wall_id=wall.id
         *
         * wall  墙表   id = wallId,  object_id = userID || spaceID
         * contentcontainer 和wall雷同，guid = user.guid || space.guid, pk=userID || spaceID, owner_user_id=userID, wall_id=wall.id
         *
         * wall_entry 发布post会产生多条记录，wall_id可以区分发布位置(space|user), content_id = [多条]content.id
         *
         * contentd 内容相关的表：guid(user|space.guid)， model:指定Post || Activity, object_id对应表post || activity 的ID
         * activity 其中model区分内容来自post或space，id区分post或spaceID
         * post     记录发布的内容！
         */
        /*
        $cClass = \Yii::$app->request->post('containerClass');
        if( $cClass == 'user' ){
            $userId = Yii::$app->user->id;
            $user = User::findOne($userId);
            if( ! $user ){
                throw new \yii\web\BadRequestHttpException('User not found');
            }
        }elseif( $cClass == 'space' ){
            $sguid = \Yii::$app->request->post('containerGuid');
            $space = Space::findOne(['guid' => $sguid]);
            if( ! $space ){
                throw new \yii\web\BadRequestHttpException('Space not found');
            }

        }else{
            throw new \yii\web\BadRequestHttpException('containerClass error');
        }
         */

        $cClass = \Yii::$app->request->post('containerClass');
        $p_type = \Yii::$app->request->post('p_type');

        if (!$this->contentContainer->permissionManager->can(new \humhub\modules\post\permissions\CreatePost())) {
            Yii::$app->params['res-success'] = false;
            return false;
        }

        $post = new Post();

        //0=图文 3=视频
        if( $cClass == 'user' ){
            if( $p_type==3 ){
                //check : video url
                //throw new \yii\web\BadRequestHttpException('p_type error.');
                $post->p_video = \Yii::$app->request->post('p_video');
                $post->p_secs  = (int)\Yii::$app->request->post('p_secs');
            }elseif( $p_type==0 ){
                //check : message is string
            }else if($p_type==4){
                $post->p_title = \Yii::$app->request->post('p_title');
            }else{
                throw new \yii\web\BadRequestHttpException('p_type error.');
            }
        //}elseif( $cClass == 'space' ){
        ////1=任务  2=课程
        //    if( $p_type == 1 ){
        //        //check : task
        //    }else{
        //        throw new \yii\web\BadRequestHttpException('p_type error.');
        //    }
        }else{
            throw new \yii\web\BadRequestHttpException('containerGuid error.');
        }


        $post->message = \Yii::$app->request->post('message');
        $post->p_type  = $p_type;
        //return \humhub\modules\content\widgets\WallCreateContentForm::create($post, $this->contentContainer);
        $res = \humhub\modules\content\widgets\WallCreateContentForm::create($post, $this->contentContainer);
        if( isset($res['postId']) ){
            return $res;
        }else{
            Yii::$app->params['res-success'] = false;
            if( isset($res['errors']) ){
                return $res['errors'];
            }else{
                return false;
            }
        }
    }

    /**
     * 分享任务结果到首页
     *
     * POST /api/postcc/task-share
     *
     * post.containerClass 发布类型，[=user]
     *
     * post.containerGuid  类型GUID，其值为别为user的guid
     *
     * post.visibility     [=1]公共
     *
     * post.p_postid       子任务的id（即postId)
     *
     * post.jobs           任务结果的id,多个结果以逗号分隔，如：1,2,3,4,5,6
     *
     * @return array 新post的id信息等
     */
    public function actionTaskShare(){
        $cClass = \Yii::$app->request->post('containerClass');
        $p_type = \Yii::$app->request->post('p_type');
        //0=图文 3=视频
        if( $cClass == 'user' ){
            //
        }else{
            throw new \yii\web\BadRequestHttpException('containerGuid error.');
        }

        if (!$this->contentContainer->permissionManager->can(new \humhub\modules\post\permissions\CreatePost())) {
            Yii::$app->params['res-success'] = false;
            return false;
        }

        $ts = \Yii::$app->request->post('jobs');
        if( count($ts) >= 255 ){
            throw new \yii\web\BadRequestHttpException('分享的任务结果过多.');
        }
        $postid = (int)\Yii::$app->request->post('p_postid');
        if( ! is_numeric($postid) ){
            throw new \yii\web\BadRequestHttpException('分享的子任务不存在.');
        }

        $post = new Post();
        $post->scenario = 'task';
        $post->message = '分享的任务结果';
        $post->p_postid= $postid;
        $post->p_type  = 11;
        $post->p_title = $ts;
        $res = \humhub\modules\content\widgets\WallCreateContentForm::create($post, $this->contentContainer);
        if( isset($res['postId']) ){
            return $res;
        }else{
            Yii::$app->params['res-success'] = false;
            if( isset($res['errors']) ){
                return $res['errors'];
            }else{
                return false;
            }
        }
    }

    /**
     * 编辑dashboard和space内容
     *
     * PUT /api/postcc
     *
     * post.Post[message]  编辑的新内容
     *
     * post.id             编辑的Post的ID
     *
     * post.containerClass 发布类型，[=user]修改dashboard的Post，[=space]修改space的space
     *
     * post.containerGuid  类型GUID，其值为别为space或user的guid
     *
     * @return boolean
     */
    public function actionEdit(){
        $id = Yii::$app->request->post('id');

        $edited = false;
        $model = Post::findOne(['id' => $id]);

        if (!$model->content->canWrite()) {
            throw new \yii\web\BadRequestHttpException('Access denied!');
        }

        if ($model->load(Yii::$app->request->post())) {
            // Reload record to get populated updated_at field
            if($model->validate() && $model->save()) {
                $model = Post::findOne(['id' => $id]);
                return true;
            }
        }
        Yii::$app->params['res-success'] = false;
        return false;
    }
}
?>
